import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';

import { Input } from '../../components/input';
import { PasswordInput } from '../../components/input/password';
import { useLoginMutation } from '../../generated/graphql';
import './index.css';

interface Props {}

export function LoginPage({}: Props) {
  const history = useHistory();

  const [userName, setUserName] = useState<string>('');
  const [password, setPassword] = useState<string>('');
  const [login, loginResult] = useLoginMutation({
    notifyOnNetworkStatusChange: true,
    onCompleted(data) {
      const jwt = data.login;
      localStorage.setItem('jwt', jwt);
      localStorage.setItem('userName', userName!);
      history.push('/');
      window.location.reload();
    },
    onError(e) {
      alert(e);
    }
  });

  const handleToRegister = () => {
    history.push('/register');
  };

  return (
    <div className="page">
      <div className="login">
        <p className="loginTitle">
          <div className="ml-8 text-xl select-none cursor-pointer">
            <span className="font-bold text-blue-800" style={{ marginRight: 1 }}>
              Byte
            </span>
            Code
          </div>
        </p>
        <p className="loginDescribe">账号</p>
        <Input
          onChange={(e) => {
            setUserName(e.currentTarget.value);
          }}
          placeholder="请输入账号"
        />
        <p className="loginDescribe" style={{ marginTop: 20 }}>
          密码
        </p>
        <PasswordInput
          onChange={(e) => {
            setPassword(e.currentTarget.value);
          }}
          placeholder="请输入密码"
        />
        <button
          className="loginButton"
          onClick={() => {
            login({
              variables: {
                userName,
                password
              }
            });
          }}
        >
          登录
        </button>
        <p className="loginToRegister">
          <span className="font1">没有账号，</span>
          <span className="font2 cursor-pointer" onClick={handleToRegister}>
            立即注册
          </span>
        </p>
      </div>
    </div>
  );
}
